/**
 * 主页
 * @type {createApplication}
 */
var express = require('express');
var router = express.Router();
var url = require('url');
var qstr = require("querystring");
var fs = require("fs");
var pro = require('../property/cuspro');
var auth = require('../auth/auth');
var util = require('../util/commonutil');
var request = require('request');
var resultJSON = require('../routes/common/resultJSON');
var redisClient = require('../property/app_redis');
var cache = require('memory-cache');

/* GET home page. */
// router.get('/', function(req, res, next) {
//   res.render('index', { title: 'Expr问问ess22-444' });
// });
var redis = require('redis'),
    RDS_PORT = 6379,        //端口号
    RDS_HOST = '172.24.164.121',    //服务器IP
    //RDS_PWD = 'porschev',    //密码
    RDS_OPTS = {},            //设置项
    client = redis.createClient(RDS_PORT,RDS_HOST,RDS_OPTS);


client.on('connect',function(){
    console.log('connect');
});
client.on('error',function(error){
    console.log(error);
});
client.on('ready',function(err){
    pro.gClient=client;
    console.log('redis connect success');
});
client.on("end", function() {
    console.log("RedisServer is end!");
});



var rootMenus = [
    {
        "id":1,
        "url":"main/mainFrame"
    },
    {
        "id":4,
        "url":"dataManage/dataManage"
    },
    {
        "id":2,
        "url":"map/newMonitor"
    },
    {
        "id":7,
        "url":"applicationManage/electronOpenManage.ejs"
    },
    {
        "id":6,
        "url":"report/reportManage"
    },
    {
        "id":3,
        "url":"systemManage/moreDataSetting"
    }
];

var sysMapMenus = [
    {
        "id":14,
        "url":"dataManage/dataManage"
    },
    {
        "id":15,
        "url":"dataManage/accountManage"
    },
    {
        "id":13,
        "url":"dataManage/deviceManage"
    },
    {
        "id":16,
        "url":"dataManage/roleManage"
    },
];

var carTree = [
];
var carTreeJson = {};
var treeItems = [];
var rootTree;
var _root =  {
    "baseProtocolType": 1,
    "code": "001",
    "deptManager": null,
    "id": 1,
    "isDeleted": false,
    "memo": null,
    "name": "GPS管理中心",
    "parentId": -1,
    "parentName": "所有客户",
    "phone": null,
    "pnum": 1,
    "uname": "GPS管理中心(0/1)",
    "work": null,
    "zx": 0
};
function getTrees(treeDatas) {
    carTree = [];
    try{
        if(treeDatas && treeDatas.length){
            for(var m=0;m<treeDatas.length;m++){
                if(treeDatas[m].parentId == -1){
                    _root = treeDatas[m]
                }
            }
            rootTree = getTreeData(treeDatas,_root);
            rootTree["text"] = "<span class='carname'>"+_root["uname"]+"</span>";
            rootTree["state"]= {
                expanded:true,
                isHideCheck:true
            };
            carTree.push(rootTree)
        }
    }catch (err){
        console.log("查询车辆树结果失败"+err)
    }
}

function getTreeData(treeDatas,treeitem) {
    try{
        if(treeDatas && treeDatas.length){
            treeitem["nodes"] = [];
            for(var i=0;i<treeDatas.length;i++){
                var _treeData = treeDatas[i];
                _treeData["text"] = "<span class='carname'>"+_treeData["uname"]+"</span>";
                _treeData["state"]= {
                    expanded:false
                };
                if(_treeData["isCar"] == true){
                    //warningType 1--在线 0-离线 2-在线停止 3-报警 5-超速
                    if(_treeData["warningType"] == 0){
                        _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-black.png'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    }else if(_treeData["warningType"] == 1 || _treeData["warningType"] == 2){
                        _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-blue.png'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    }
                    else if(_treeData["warningType"] == 3 || _treeData["warningType"] == 5 || _treeData["warningType"] == 8){
                        _treeData["text"] = "<span class='icon btnImage isCar'><img src='images/page3/round-red.png'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    } else{
                        _treeData["text"] = "<span class='icon isCar'></span><span class='carname'>"+_treeData["text"]+"</span>";
                    }
                    if(!carTreeJson[_treeData["baseTerminalId"]]){
                        carTreeJson[_treeData["baseTerminalId"]] = _treeData;
                    }
                }else{
                    _treeData["state"]["isHideCheck"]= true;
                    if(_treeData["uname"].indexOf("无线设备(") == -1 && _treeData["uname"].indexOf("有线设备(") == -1){
                        _treeData["state"]["expanded"]= true;
                    }
                }
                if(_treeData["parentId"] == treeitem["id"]){
                    treeitem["nodes"].push(getTreeData(treeDatas,_treeData));
                }
            }
            return treeitem
        }
    }catch (err){
        console.log("查询车辆树结果失败"+err)
    }
};

router.get('/', function(req, res, next) {
    res.render('newLogin',{nosuccess:"",message:""});
});

router.post('/index', function(req, res, next) {

    //ajax请求返回user对象
    // var user=null;
    // auth.dologin(req, res, next,user);
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid=sid;
    //res.redirect('/index');
    // {serverurl:pro.serveraddr,menus:data.parentMenuList,menuItems:data.sysMap,userName:data.userName,userId:data.userId,roleName:data.roleName});
    console.log("登陆参数>>"+JSON.stringify(qs));
    request({
        url: pro.serveraddr+'/login/employeeLogin',
        method: "POST",
        qs: qs
    }, function(error, response, body){
        console.log(response.statusCode);
        console.log(error);
        if (!error && response && response.statusCode == 200) {
            try{
                var data=JSON.parse(body);
                console.log("--登录数据body成功--");
                if(data && data.success){
                    console.log("--登录数据body成功1--");
                    var _pMList = data.parentMenuList;
                    var _sysList = data.sysMap;
                    var _renderUrl = "";
                    var treeJson = data.tree;
                    var treeCount = data.data;
                    var deptCarIds = data.deptCarIds;
                    var _roleId = data.roleId;
                    pro.loginUserId = data["userId"];
                    client.get("carTreeObj_"+data["userId"],function (error, resu) {
                        if(error) {
                            console.log(error);
                        } else {
                            cache.del("cacheCarTreeObj_"+data["userId"]);
                            cache.put("cacheCarTreeObj_"+data["userId"],JSON.parse(resu));
                        }
                    });
                    if(_pMList && _pMList.length){
                        for(var k=0;k<rootMenus.length;k++){
                            var _menuId =rootMenus[k]["id"];
                            if(_renderUrl){
                                break;
                            }
                            for(var a=0,_len=_pMList.length;a<_len;a++){
                                if(_menuId == _pMList[a]["id"]){
                                    if(_menuId == 4){
                                        for(var g=0,g_len=sysMapMenus.length;g<g_len;g++){
                                            if(_renderUrl){
                                                break;
                                            }
                                            for(var t=0,
                                                    t_len=_sysList.length;t<t_len;t++){
                                                if(sysMapMenus[g]["id"] == _sysList[t]["id"]){
                                                    _renderUrl = sysMapMenus[g]["url"];
                                                    break;
                                                }
                                            }
                                        }
                                    }else{
                                        _renderUrl = rootMenus[k]["url"];
                                    }
                                    break;
                                }
                            }
                        }
                        pro.carTrees["carTreeCount"] = treeCount;
                        pro.carTrees["offLineCar"]=data.offlineStr;
                        pro.carTrees["onLineCar"]=data.onlineStr;
                        cache.put("carTrees",pro.carTrees);
                        // console.log(treeJson);
                        // console.log(treeCount);
                        try {
                            if(treeJson){
                                console.log("--登录数据treeJson--");
                                //getTrees(JSON.parse(treeJson));

                                // pro.carTreeObj={
                                //     carTree:carTree,
                                //     carTreeJson:carTreeJson
                                // };
                                console.log("--登录数据treeJson成功--");
                                //cache.put("carTreeObj",pro.carTreeObj);
                                // req.session.treeData = {treeJson:treeJson};
                            }else{
                                // pro.carTreeObj = {};
                            }
                            console.log(deptCarIds);
                            if(deptCarIds){
                                console.log("--登录数据deptCarIds--");
                                cache.put("deptCarIds",JSON.parse(deptCarIds));
                                console.log("--登录数据deptCarIds成功--");
                            }

                        }catch (e){
                            req.session.treeData = [];
                        }
                        res.render(_renderUrl,{parentMenuList:JSON.stringify(data.parentMenuList),sysMap:JSON.stringify(data.sysMap),allMenus:data.allMenus,serverurl:pro.serveraddr,pointCarId:"",baseCarNo:"",sessionSid:sid,roleName:data.roleName,roleId:_roleId});
                    }else{
                        resultJSON.isSuccess = false;
                        resultJSON.message = data.msg;
                        console.log("error= " + data.msg);
                        // res.redirect('/',{success:false,message:data.msg});
                        res.render('newLogin',{nosuccess:true,message:"您没有任何权限，无法登陆！"});
                    }

                    //console.log("登录返回信息>>"+JSON.stringify(data.parentMenuList));
                    // res.render('main/mainFrame',{serverurl:pro.serveraddr,menus:data.parentMenuList,menuItems:data.sysMap,userName:data.userName,userId:data.userId,roleName:data.roleName});
                }else {
                    resultJSON.isSuccess = false;
                    resultJSON.message = data.msg;
                    console.log("error= " + data.msg);
                    // res.redirect('/',{success:false,message:data.msg});
                    res.render('newLogin',{nosuccess:true,message:data.msg});
                    //res.json(resultJSON)
                }
            }catch (e) {
                console.log("登录信息>>"+body);
                console.log(e.message);
                res.redirect('/');
            }
        }else{
            res.redirect('/');
        }
    });
});

router.get('/logout', function(req, res, next) {

    //ajax请求返回user对象
    // var user=null;
    // auth.dologin(req, res, next,user);
    var sid=auth.getSessionID(req, res, next);
    var qs=req.body;
    qs.sid=sid;
    //res.redirect('/index');
    // {serverurl:pro.serveraddr,menus:data.parentMenuList,menuItems:data.sysMap,userName:data.userName,userId:data.userId,roleName:data.roleName});
    request({
        url: pro.serveraddr+'/login/logout',
        method: "POST",
        qs: qs
    }, function(error, response, body){
        //console.log("退出登录信息>>"+body);
        // if (!error && response.statusCode == 200) {
        //     var data=JSON.parse(body);
        //
        //     if(data && data.success){
        //         res.render('main/mainFrame');
        //         //res.render('main/index',{serverurl:pro.serveraddr,menus:data.parentMenuList,menuItems:data.sysMap,userName:data.userName,userId:data.userId,roleName:data.roleName});
        //     }else {
        //         resultJSON.isSuccess = false;
        //         resultJSON.message = data.msg;
        //         console.log("error= " + data.msg);
        //         // res.redirect('/',{success:false,message:data.msg});
        //         res.render('newLogin',{nosuccess:true,message:data.msg});
        //         //res.json(resultJSON)
        //     }
        // }else{
        //     res.redirect('/');
        // }
        res.redirect('/');
    });
});


router.post('/changePwd', function(req, res, next) {
    //登录
    var sid=auth.getSessionID(req, res, next);
    // var arg = url.parse(req.url, true).query;   //arg1 => {name:'a',id:'5'}
    //
    // arg.sid=sid;
    var qs=req.body;
    qs.sid=sid;
    console.log("qs>>"+JSON.stringify(qs));
    request({
        url: pro.serveraddr+'/login/doChangePwd',
        method: "POST",
        qs: qs
    }, function(error, response, body){
        if (!error && response.statusCode == 200) {
            var data=JSON.parse(body);
            res.json(data);
        }
    });
});

module.exports = router;
